﻿using System;
using System.Collections;
using System.Collections.Generic;
using Eamon.MeituanDotnetSDK.api.common;
using Eamon.MeituanDotnetSDK.httpclient;
using Eamon.MeituanDotnetSDK.utils;

namespace Eamon.MeituanDotnetSDK.executor
{
    public class SignExecutor : AbstractExecutor, Executor
    {
        public SignExecutor()
        {
        }
        private string bizParams;
        private string appAuthToken;
        private readonly string signKey;
        private readonly long developerId;

        //是否替换session为appAuthToken以兼容老版本
        private bool replaceSession = false;

        public SignExecutor(OpenAPIHttpClient httpClient, string appAuthToken, string bizParams, string signKey, long developerId)
        {
            this.appAuthToken = appAuthToken;
            this.bizParams = bizParams;
            this.signKey = signKey;
            this.developerId = developerId;
            this.httpClient = httpClient;
        }
        public SignExecutor(OpenAPIHttpClient httpClient, bool replaceSession, string signKey, long developerId)
        {
            this.replaceSession = replaceSession;
            this.signKey = signKey;
            this.developerId = developerId;
            this.httpClient = httpClient;
        }



        protected override void prepare(ExecutionContext context)
        {
            IAPI api = context.getApi();
            Dictionary<string, object> paramters = api.getAPIRequest().toParams();
            if (replaceSession)
            {
                appAuthToken = paramters["session"].ToString();
                paramters.Remove("session");
                bizParams = JsonUtil.ToJson(paramters);
            }
            Hashtable executeParams = [];
            executeParams.Add(CommonConstants.CHARSET, CommonConstants.CHARSET_UTF8);
            executeParams.Add(CommonConstants.DEVELOPER_ID, developerId);
            executeParams.Add(CommonConstants.TIMESTAMP, TimeUtil.formatTime(DateTimeOffset.Now));
            foreach (var kv in paramters)
            {
                if (kv.Value is DateTimeOffset v)
                {
                    string date = TimeUtil.formatTime(v);
                    executeParams.Add(kv.Key, date);
                }
                else
                {
                    executeParams.Add(kv.Key, kv.Value);
                }
            }
            executeParams.Add(CommonConstants.VERSION, "2");
            executeParams.Add(CommonConstants.BUSINESS_ID, "58");//TODO:业务id目前只支持58到店综合
            executeParams.Add(CommonConstants.APP_AUTH_TOKEN, appAuthToken);
            executeParams.Add(CommonConstants.BIZ_FIELD, bizParams);
            string paramSign = EncryptUtil.getSign(signKey, executeParams);
            executeParams.Add(CommonConstants.SIGN, paramSign);
            context.setParams(executeParams);
            context.setUrl(api.getHttpUrl());
        }
    }
}
